import { MachineBase } from "@/Battle/StateMechine/MachineBase.js";

import { BattleEventType } from "@/Battle/Event/BattleEvent.js";
import CombatEventBus from "@/Battle/CombatEventBus.js";
import { CombatEventPool } from "@/Battle/Event/CombatEventPool.js";
import { BattleManager } from "@/managers/BattleManager.js";

//一个角色的回合
export class TurnMechine extends MachineBase {
    constructor() {
        super();
        this.battler = null;
        this.payload = { target: null };
        this.addStateHandler('start', this.onStartTurnRequest);
        this.addStateHandler('end', this.onEndTurnRequest);
    }

    currentTurnBattler() {
        return this.battler;
    }

    onStartTurnRequest = () => {
        this.wait();
        this.battler = BattleManager.peekNextBattler();
        this.payload.target = this.battler;
        if (!this.battler) {
            this.toback();
        } else {
            CombatEventBus.dispatch(
                CombatEventPool.newCombatEvent(
                    BattleEventType.Turn.Start.Request,
                    this,
                    this.payload
                ),
                this.startTurn,
                this.onEndTurnRequest
            );
        }
    }

    startTurn = () => {
        //选出行动角色，并处理好行动次数
        let battle = BattleManager.peekNextBattler();
        if (battle != this.battler) {
            //被拦截了
            this.start();
        } else {
            this.battler = BattleManager.getNextBattler();//获取真正的battler
            this.payload.target = this.battler;
            this.battler.makeActions();
            CombatEventBus.dispatch(
                CombatEventPool.newCombatEvent(
                    BattleEventType.Turn.Start.Complete,
                    this,
                    this.payload
                ),
                this.startAction,
                this.onEndTurnRequest
            );
        }
    }

    startAction = () => {
        this.tonext();
        this.end();
    }

    onEndTurnRequest = () => {
        this.wait();
        CombatEventBus.dispatch(
            CombatEventPool.newCombatEvent(
                BattleEventType.Turn.End.Request,
                this,
                this.payload
            ),
            this.endTurn,
            this.onSkip
        );
    }

    endTurn = () => {
        BattleManager.releaseBattler(this.battler);

        CombatEventBus.dispatch(
            CombatEventPool.newCombatEvent(
                BattleEventType.Turn.End.Complete,
                this,
                this.payload
            ),
            this.start,
            this.onSkip
        );
        this.battler = null;
    }


    onSkip = () => {
        this.toback();
        this.battler = null;
    }
}